package com.animerank.controller;

import com.animerank.dto.Result;
import com.animerank.service.IDoubanService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * 豆瓣搜索控制器
 */
@RestController
@RequestMapping("/douban")
@Tag(name = "豆瓣搜索", description = "豆瓣动漫搜索相关接口")
public class DoubanController {

    @Autowired
    private IDoubanService doubanService;

    /**
     * 搜索豆瓣动漫
     * @param q 搜索关键词
     * @return 搜索结果
     */
    @GetMapping("/search")
    @Operation(summary = "搜索豆瓣动漫", description = "根据关键词搜索豆瓣动漫信息")
    public Result<?> searchDoubanAnime(@RequestParam String q) {
        return doubanService.searchDoubanAnime(q);
    }

    /**
     * 图片代理接口，用于解决防盗链问题
     * @param url 图片原始URL
     * @return 图片数据
     */
    @GetMapping("/image-proxy")
    @Operation(summary = "图片代理", description = "代理获取图片，解决防盗链问题")
    public ResponseEntity<?> proxyImage(@RequestParam String url) {
        Result<byte[]> result = doubanService.proxyImage(url);
        
        if (!result.isSuccess()) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .contentType(MediaType.APPLICATION_JSON)
                .body(result);
        }
        
        byte[] imageData = result.getData();
        HttpHeaders headers = new HttpHeaders();
        
        // 设置响应头
        headers.setContentType(MediaType.IMAGE_JPEG);
        headers.setContentLength(imageData.length);
        headers.setCacheControl(CacheControl.maxAge(1, TimeUnit.HOURS).cachePublic());
        
        return new ResponseEntity<>(imageData, headers, HttpStatus.OK);
    }
    
    /**
     * 获取豆瓣动漫详情
     * @param id 豆瓣动漫ID
     * @return 详情HTML内容
     */
    @GetMapping("/detail")
    @Operation(summary = "获取豆瓣动漫详情", description = "根据豆瓣ID获取动漫详情页面HTML")
    public Result<?> getDoubanDetail(@RequestParam String id) {
        return doubanService.getDoubanDetail(id);
    }
}